package com.dayu.finecomm.iot.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.iot.IotDriverAdapter;
import com.dayu.finecomm.iot.device.IotPlatDevice;
import com.dayu.finecomm.iot.ssl.SslContextFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * IotPlat的web service，用于获取iot平台的订阅响应
 * @author XuJialiang
 * @since 2017-09-04 10:22:12
 * @version V1.0.0
 */
public class IotPlatServer {
	static Logger LOGGER = LoggerFactory.getLogger(IotPlatServer.class);
	
	/**
	 * IotPlat协议Handler
	 */
	IotPlatDevice mHandler;
	
	/**
	 * HttpServer host
	 */
	String mHost;
	
	/**
	 * 监听端口号
	 */
	int mPort;
	
	public IotPlatServer(String host, int port, IotDriverAdapter adapter) {
		mHost = host;
		mPort = port;
		mHandler = new IotPlatDevice(mHost, mPort, adapter, SslContextFactory.getServerContext());
	}
	
	/**
	 * 启动HTTP Server
	 * @return ChannelFuture
	 * @throws InterruptedException
	 */
	public ChannelFuture bootstrap() throws InterruptedException {

		final EventLoopGroup boss = new NioEventLoopGroup();
		final EventLoopGroup workers = new NioEventLoopGroup();

		ServerBootstrap b = new ServerBootstrap();
		b.channel(NioServerSocketChannel.class);
		b.group(boss, workers);

		b.childHandler(mHandler);

		ChannelFuture f = null;
		if (mHost.isEmpty()) {
			f = b.bind(mPort).sync();
		} else {
			f = b.bind(mHost, mPort).sync();
		}
		
		LOGGER.info("start httpserver success");

		ChannelFuture cf = f.channel().closeFuture();

		cf.addListener(new GenericFutureListener<Future<? super Void>>() {

			@Override
			public void operationComplete(Future<? super Void> future)
					throws Exception {
				boss.shutdownGracefully();
				workers.shutdownGracefully();
			}
		});

		return cf;
	}
}
